const Koa = require('koa')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const koa2Cors = require('koa2-cors')
const { initConfig, initConctroller, initService, initExtend, initModel, initMiddleware, initPlugin, initRouter } = require('./loader')
const { port, staticPath } = require('../../config')
const koaParamValidate = require('koa-param-validate')

class App {
  constructor() {
    this.app = new Koa()

    koaParamValidate(this.app)

    this.initCommonMiddleware()

    this.config = initConfig(this)
    this.controller = initConctroller(this)
    this.service = initService(this)
    this.model = initModel(this)
    this.middleware = initMiddleware(this)
    this.router = initRouter(this)

    // 注册路由
    this.app.use(this.router.routes()).use(this.router.allowedMethods())
  }

  // 配置通用中间件
  initCommonMiddleware () {
    // 挂载ctx
    this.app.use(async (ctx, next) => {
      this.ctx = ctx
      initExtend(this) // 将extend挂载到ctx上
      await next()
    })
    // 解释post请求
    this.app.use(koaBody({
      multipart: true // 支持文件上传
    }))
    // 静态资源访问
    this.app.use(koaStatic(staticPath), {
      gzip: true
    })
    // 跨域
    this.app.use(koa2Cors({
        origin: (ctx) => {
            return '*'
        }
    }))
  }

  // 启动服务
  start () {
    this.app.listen(port, () => {
      console.log(`server is running on http://localhost:${port}`)
    })
  }
}

module.exports = App